import { useState, useEffect } from "react";
import { Form, Input, Row, Col, Select, Modal, Alert, message, InputNumber, Cascader } from "antd";
import { CommonModal } from "@/views/components/CommonModal";
import { upadteGoods, getPriceTip } from "../service";
import { getCurrentUser } from "@/utils/authority";
import CommonInput from "@/pages/OrderModule/common/components/CommonInput";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
const { TextArea } = Input;
import Typography from "@/pages/OrderModule/common/components/Typography";
//批量改价
const BulReprice = ({ query, checkedRows, fetchList, handleOk, handleCancel, dataSource, visible }) => {
	const [form] = Form.useForm();
	const [loading, setLoading] = useState(false); //loading
	const [goodsNum, setGoodsNum] = useState(0);
	const [type, setType] = useState("=");
	const [tipVisible, setTipVisible] = useState(0);
	const [price, setPrice] = useState(0);
	const [priceData, setPriceData] = useState({});
	const [isNeedPay, setIsNeedPay] = useState(0);

	const getPriceTipFn = async () => {
		if (checkedRows.length > 0) {
			const filteredData = checkedRows.filter(item => item.hasOwnProperty("skuId"));
			const mergedOutboundProductIds = dataSource.flatMap(item => item.children.map(child => child.outboundProductIds));

			const finalArray = mergedOutboundProductIds.reduce((acc, ids) => [...acc, ...ids], []);
			const skuIdsWithType1 = filteredData.filter(item => item.priceType === 1).map(item => item.skuId);
			const skuIdsWithType2 = filteredData.filter(item => item.priceType === 2).map(item => item.skuId);
			let purchasePrice = {
				ids: skuIdsWithType1,
				type: type,
				price: price
			};
			let vipPrice = {
				ids: skuIdsWithType2,
				type: type,
				price: price
			};
			let param = {
				purchasePrice: purchasePrice,
				vipPrice: vipPrice,
				uuid: getCurrentUser().uuid,
				pwd: "",
				type: "web"
			};
			const { data, success } = await getPriceTip(param);
			if (success) {
				if (data.changeBalanceAmount == 0 && data.changeCreditAmount == 0) {
					requrestFn();
				} else {
					setPriceData(data);
					setTipVisible(1);
				}
			}
		}
	};
	useEffect(() => {
		form.resetFields();
	}, []);

	useEffect(() => {
		const filteredData = checkedRows.filter(item => item.hasOwnProperty("skuId"));
		const totalPrice = filteredData.reduce((acc, item) => acc + item.skuPrice, 0);
		if (priceData.changeBalanceAmount - totalPrice > 0) {
			setIsNeedPay(1);
		}
	}, [tipVisible]);

	useEffect(() => {
		if (checkedRows.length > 0) {
			const filteredData = checkedRows.filter(item => item.hasOwnProperty("skuId"));
			setGoodsNum(filteredData.length);
		}
	}, [visible]);
	const requrestFn = () => {
		form.validateFields().then(async value => {
			const filteredData = checkedRows.filter(item => item.hasOwnProperty("skuId"));
			const skuIdsWithType1 = filteredData.filter(item => item.priceType === 1).map(item => item.skuId);
			const skuIdsWithType2 = filteredData.filter(item => item.priceType === 2).map(item => item.skuId);
			let purchasePrice = {
				ids: skuIdsWithType1,
				type: type ? type : "=",
				price: value.price,
				pwd: value.payPwd
			};
			let vipPrice = {
				ids: skuIdsWithType2,
				type: type ? type : "=",
				price: value.price,
				pwd: value.payPwd
			};
			let param = {
				purchasePrice: purchasePrice,
				vipPrice: vipPrice,
				isNeedPay: priceData.changeBalanceAmount > 0 ? 1 : 0,
				uuid: getCurrentUser().uuid,

				type: "app"
			};

			const { success } = await upadteGoods(param);
			if (success) {
				message.success("操作成功");
				fetchList();
				onCancel();
			}
			setLoading(false);
		});
	};
	const onOk = () => {
		requrestFn();
	};

	const undatePriceOK = async () => {
		// requrestFn();
		getPriceTipFn();
	};
	const onChange = e => {
		setType(e);
	};
	const handleBlur = async event => {
		setPrice(event.target.value);
	};
	const onCancel = () => {
		handleCancel();
		form.resetFields();
	};
	return (
		<CommonModal title={{ title: "批量改价" }} visible={true} onOk={undatePriceOK} onCancel={handleCancel}>
			<Form form={form} name="stock-set-remark-modal">
				<Alert
					style={{ marginBottom: 16 }}
					showIcon
					message={<Typography as="s1">注：批量改价，有商品价格相同的将会跳过</Typography>}
				/>
				<SubTitle symbol as="s2" title="改价详情" style={{ marginBottom: 16 }} />
				<div style={{ margin: "12px   0 16px 16px" }}>商品种类数：{goodsNum}</div>
				<Row>
					<Col span={23} style={{ marginLeft: 16 }}>
						<Form.Item name="price" label="" style={{ border: "1px solid rgba(0, 104, 255, 1)", borderRadius: 5 }}>
							<Input
								style={{ width: "100%" }}
								suffix="元"
								onBlur={handleBlur}
								type="number"
								addonBefore={
									<Select
										placeholder="统一改为"
										style={{ width: 100 }}
										defaultValue={"="}
										onChange={onChange}
										options={[
											{
												value: "=",
												label: "统一改为"
											},
											{
												value: "+",
												label: "统一上调"
											},
											{
												value: "-",
												label: "统一下调"
											}
										]}
									/>
								}
							/>
						</Form.Item>
					</Col>
				</Row>
			</Form>
			{tipVisible == 1 && (
				<CommonModal title={{ title: "改价提示" }} visible={true} onOk={onOk} onCancel={handleCancel}>
					<Form form={form} name="stock-set-remark-modal">
						<Alert
							style={{ marginBottom: 16 }}
							showIcon
							message={<Typography as="s1">改价后，金额会进行多退少补如下，请确认是否确认改价?</Typography>}
						/>
						{isNeedPay == 1 && <div style={{ margin: "12px   0 16px 16px" }}>余额补扣：{priceData.changeBalanceAmount}</div>}
						{isNeedPay == 1 && <div style={{ margin: "12px   0 16px 16px" }}>账户余额：{priceData.availBalance}</div>}
						{isNeedPay == 0 && (
							<div style={{ margin: "12px   0 16px 16px" }}>
								<span>{priceData.changeBalanceAmount > 0 ? "余额补扣" : "余额退回"}</span>:
								{Math.abs(priceData.changeBalanceAmount)}
							</div>
						)}
						{isNeedPay == 0 && (
							<div style={{ margin: "12px   0 16px 16px" }}>账期退回:{Math.abs(priceData.changeCreditAmount)}</div>
						)}
						{isNeedPay == 1 && (
							<Row>
								<Col span={23} style={{ marginLeft: 16 }}>
									<Form.Item name="payPwd" rules={[{ required: true, message: "请输入支付密码" }]}>
										<CommonInput Component={Input} placeholder="请输入支付密码" aria-required />
									</Form.Item>
								</Col>
							</Row>
						)}
					</Form>
				</CommonModal>
			)}
		</CommonModal>
	);
};

export default BulReprice;
